<template>
  <div>
    <el-form
      ref="ruleForm"
      inline
      label-width="120"
      :rules="rules"
      :model="formData"
    >
      <el-form-item label="生效时间" prop="effectiveFrom">
        <el-date-picker
          v-model="formData.effectiveFrom"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetime"
          placeholder="选择日期"
        />
      </el-form-item>
      <el-form-item label="分区方案" prop="zoneId">
        <el-select v-model="formData.zoneId" style="width: 200px;" @on-change="cleanHandleTable">
          <el-option v-for="item in zoneOptions" :key="item.code" :label="item.name" :value="item.code" />
        </el-select>
      </el-form-item>
      <el-form-item label="重量段方案" prop="weightId">
        <el-select v-model="formData.weightId" style="width: 200px;" @on-change="cleanHandleTable">
          <el-option v-for="item in weightOptions" :key="item.code" :label="item.name" :value="item.code" />
        </el-select>
      </el-form-item>
      <el-form-item label="分区排列">
        <el-radio-group v-model="formData.zoneDirection" @on-change="zoneDirectionChanged">
          <el-radio label="横向" />
          <el-radio label="纵向" />
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="drawTable">生成价格模板</el-button>
      </el-form-item>
    </el-form>
    <div v-show="handleTable" ref="hotTable" />
  </div>
</template>

<script>
import 'handsontable/dist/handsontable.full.css'
import Handsontable from 'handsontable'
import request from '@/utils/request'
import { copyProperty } from '@/utils/tools'
export default {
  name: 'BasePriceNew',
  data() {
    return {
      formDataDefault: {
        effectiveFrom: '',
        zoneId: '',
        weightId: '',
        basePrice: [],
        zoneDirection: '横向'
      },
      formData: {
        effectiveFrom: '',
        zoneId: '',
        weightId: '',
        basePrice: [],
        zoneDirection: '横向'
      },
      zoneOptions: [],
      zoneIdToSpecs: new Map(),
      weightOptions: [],
      weightIdToSpecs: new Map(),
      handleTable: null,
      initData: [],
      dfId: undefined,
      rules: {
        zoneId: [{ required: true, message: '分区方案是必选项', trigger: 'change' }],
        weightId: [{ required: true, message: '重量模板是必选项', trigger: 'change' }]
      }
    }
  },
  created() {
    this.loadZoneOption()
    this.loadWeightOption()
  },
  methods: {
    zoneDirectionChanged() {
      if (this.dfId) {
        this.loadBasePriceDetail()
        return
      }
      this.drawTable()
    },
    clean() {
      this.initData = []
      copyProperty(this.formData, this.formDataDefault)
      this.cleanHandleTable()
    },
    effectiveFromChanged(v) {
      this.formData.effectiveFrom = v
    },
    loadZoneOption() {
      request({
        url: 'zone/option',
        method: 'get'
      }).then(res => {
        if (res.success) {
          this.zoneOptions = res.data
          res.data.forEach(e => {
            this.zoneIdToSpecs.set(e.code, e.specs)
          })
        }
      })
    },
    loadWeightOption() {
      request({
        url: 'weight/option',
        method: 'get'
      }).then(res => {
        if (res.success) {
          this.weightOptions = res.data
          res.data.forEach(e => {
            this.weightIdToSpecs.set(e.code, e.specs)
          })
        }
      })
    },
    edit(data) {
      copyProperty(this.formData, data)
      this.dfId = data.dfId
      this.loadBasePriceDetail()
    },
    loadBasePriceDetail() {
      request({
        url: '/channel/base-price-detail?dfId=' + this.dfId + '&zoneDirection=' + this.formData.zoneDirection,
        method: 'get'
      }).then(res => {
        if (res.success) {
          this.initData = res.data
          this.drawTable()
        }
      })
    },
    drawTable() {
      const container = this.$refs.hotTable
      container.innerHTML = ''
      const { zoneId, weightId } = this.formData
      if (!zoneId || !weightId) {
        this.$Message.warning('请先选择分区方案和重量段方案')
        return
      }
      const zoneData = this.zoneIdToSpecs.get(zoneId)
      const weightData = this.weightIdToSpecs.get(weightId)
      let rowSize = weightData.length
      let colSize = zoneData.length
      let colHeaders = zoneData.map((item) => item.name)
      let rowHeaders = weightData.map((item) => item.name)
      let columns = zoneData.map((item) => {
        return {
          data: item.code
        }
      })
      if (this.formData.zoneDirection === '纵向') {
        rowSize = zoneData.length
        colSize = weightData.length
        colHeaders = weightData.map((item) => item.name)
        rowHeaders = zoneData.map((item) => item.name)
        columns = weightData.map((item) => {
          return {
            data: item.code
          }
        })
      }
      this.handleTable = new Handsontable(container, {
        data: this.initData,
        minSpareRows: rowSize,
        maxRows: rowSize,
        minSpareCols: colSize,
        maxCols: colSize,
        stretchH: 'all',
        width: '100%',
        height: '350px',
        autoColumnSize: false,
        autoRowSize: false,
        colHeaders: colHeaders,
        columns: columns,
        rowHeaders: rowHeaders,
        licenseKey: 'non-commercial-and-evaluation'
      })
      this.initData = []
    },
    doValidate() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const SourceData = this.handleTable?.getSourceData()
          if (!SourceData) {
            this.$Message.warning('点击生成价格模板')
            return
          }
          this.formData.basePrice = []
          const weightData = this.weightIdToSpecs.get(this.formData.weightId)
          const zoneData = this.zoneIdToSpecs.get(this.formData.zoneId)
          for (let i = 0; i < SourceData.length; i++) {
            const item = SourceData[i]
            try {
              Object.keys(item).forEach(key => {
                if (this.formData.zoneDirection === '横向') {
                  this.formData.basePrice.push({
                    'price': item[key],
                    'weightSpecId': weightData[i].code,
                    'zoneSpecId': String(key)
                  })
                } else {
                  this.formData.basePrice.push({
                    'price': item[key],
                    'weightSpecId': String(key),
                    'zoneSpecId': zoneData[i].code
                  })
                }
              })
            } catch (error) {
              console.log(error)
            }
          }
          if (this.formData.basePrice.length === 0) {
            this.$Message.warning('价格模板数据为空')
            return
          }
          this.$emit('basePriceOk', this.formData)
        } else {
          this.$Message.warning('请填写完整运费配置信息!')
        }
      })
    },
    cleanHandleTable() {
      this.formData.basePrice = []
      this.handleTable?.clear()
      this.handleTable = null
      const container = this.$refs.hotTable
      container.innerHTML = ''
    }
  }
}
</script>
